<template>
  <div class="dictionary-detail">
    <DFPageDetail ref="dfPageDetailRef" :pageOptions="pageOptions">
      <template #dictDataList>
        <div class="basicInfo-header">
          <h3>{{ t('dictionary.dicDataInfo') }}</h3>
          <ul class="language-select">
            <li
              v-for="(item, index) in selectLanguageType"
              :key="index"
              :class="item.active === 1 ? 'active' : ''"
              @click="selectLanguage(index)"
            >
              {{ item.title }}
            </li>
          </ul>
        </div>

        <DFTable
          ref="dictDataTableRef"
          routeName="dictionary"
          hasSelection
          noDefaultLoad
          :columns="tableColumns"
          :request="loadTableDataFn"
          :row-key="(row) => row.id"
          :actionColumn="tableActionColumn"
          :operaColumn="tableOperaColumn"
          @updateCheck="handleCheckedChange"
        />
      </template>
    </DFPageDetail>
    <DFModal ref="dfModalRef" @register="modalRegister" @on-ok="modalSubmitFn">
      <template #default>
        <DFForm
          label-placement="top"
          class="basicForm"
          getLabelForm="table"
          routeName="dictionary"
          @register="modalFormRegister"
        />
      </template>
    </DFModal>
  </div>
</template>

<script lang="ts" setup name="DictionaryDetails">
  import { useRoute } from 'vue-router';
  import { DFTable, DFTableAction } from '@/components/DFTable';
  import { DFModal, useModal } from '@/components/DFModal';
  import { DFForm, useForm } from '@/components/DFForm/index';
  import { useMixins } from '@/hooks/useMixins';
  import {
    getDictTypeDetail,
    getDictDataList,
    addDictData,
    updateDictData,
    removeDictData,
  } from '@/api/system/dictionary';

  import { checkZhCodeFn } from '@/utils/formCheck';

  import lang from './lang';
  import { t } from '@/i18n';
  const { loadLangFn, handleDeleteFn, message } = useMixins();
  loadLangFn(lang);

const route = useRoute();

let dictTypeCode = (toRaw(route)?.query)?.dictTypeCode || '';

  const dfPageDetailRef: any = ref(null);
  const dictDataTableRef: any = ref(null);
  const selectLanguageType = ref([
    { active: 0, title: t('dictionary.selectLangTip') },
    { active: 1, title: t('dictionary.selectLangAll') },
    { active: 0, title: '简体中文' },
    { active: 0, title: 'English' },
  ]);
  const queryLanguageType = ref('');

  const editDisabled = ref(false);
  const languageList = ref([{
    label: '简体中文',
    value:'zh'
  },{
    label: 'English',
    value:'en'
  }]);

  const currentCheckedRowKeys = ref([]);
  const deleteDisabled = ref(true);

  const pageOptions = {
    routeName: 'dictionary',
    getDataFn: getDictTypeDetail,
    handleEditDataFn: (res) => {
      // dictTypeCode = res?.data?.dictionaryTypeCode;
      reloadTableFn();
      return res?.data || {};
    },
    list: [
      {
        type: 'form',
        descriptionsLabelWidth: 110,
        formSchemas: [
          {
            label: 'dictTypeCode',
            prop:'dictionaryTypeCode'
          },
          {
            label: 'dictTypeName',
            prop:'dictionaryTypeName',
            span:3
          },
          {
            label: 'remark',
            prop: 'remark',
            span:3
          },
        ],
      },
      {
        type: 'slot',
        hiddenTitle: true,
        slotName: 'dictDataList',
      },
    ],
  };

  const tableColumns = [
    {
      width: 60,
      type: 'selection',
      key: 'selection',
      fixed: 'left',
    },
    { label: 'languageType', key: 'languageType',render:(row)=>h('span',{innerText:`${row.languageType === 'zh'?'简体中文':'English'}`}) },
    { label: 'dictValue', key: 'dictionaryCode' },
    { label: 'dictionaryName', key: 'dictionaryName' },
    { label: 'extend1',key: 'extend1' },
    { label: 'extend2',key: 'extend2' },
    { label: 'dictSort', key: 'sort' },
    { label: 'remark', key: 'remark' },
  ];

  const tableActionColumn = reactive({
    width: 150,
    widthEn: 180,
    label: 'operation',
    key: 'action',
    fixed: 'right',
    common: true,
    render(record) {
      const recordRow = toRaw(record);

      return h(DFTableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'primary',
            label: 'edit',
            prop: 'edit',
            onClick: () => {
              openModalFn('edit', recordRow);
            },
          },
          {
            type: 'primary',
            label: 'copy',
            prop: 'copy',
            onClick: () => {
              openModalFn('copy', recordRow);
            },
          },
          {
            type: 'primary',
            label: 'delete',
            prop: 'delete',
            onClick: () => {
              handleDeleteFn([recordRow.id], removeDictData, reloadTableFn);
            },
          },
        ],
      });
    },
  });
  const tableOperaColumn = reactive([
    {
      label: 'add',
      prop: 'add',
      bind: {
        type: 'primary',
        'on-click': () => {
          openModalFn('add');
        },
      },
    },
    {
      label: 'delete',
      bind: {
        disabled: deleteDisabled,
        'on-click': () => {
          handleDeleteFn(
            currentCheckedRowKeys.value,
            removeDictData,
            reloadTableFn
          );
        },
      },
    },
  ]);

  const modalFormSchemas: any = [
    {
      field: 'languageType',
      component: 'NSelect',
      label: 'languageType',
      defaultValue: null,
      componentProps: {
        disabled: editDisabled,
        options: languageList,
      },
      rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['change'] }],
    },
    {
      field: 'dictionaryCode',
      component: 'NInput',
      label: 'dictValue',
      defaultValue: '',
      componentProps: {
        disabled: editDisabled,
        maxlength: 20,
        clearable: true,
      },
      rules: [
        {
          validator(_rule: any, value: string) {
            return checkZhCodeFn(value, true);
          },
          required: true,
          trigger: ['blur'],
        },
      ],
    },
    {
      field: 'dictionaryName',
      component: 'NInput',
      label: 'dictionaryName',
      defaultValue: '',
      componentProps: {
        maxlength: 100,
        clearable: true,
      },
      rules: [{ required: true, message: t('common.formTipMsg.input'), trigger: ['blur'] }],
    },
    {
      field: 'extend1',
      component: 'NInput',
      label: 'extend1',
      defaultValue: '',
      componentProps: {
        maxlength: 100,
        clearable: true,
      },
    },
    {
      field: 'extend2',
      component: 'NInput',
      label: 'extend2',
      defaultValue: '',
      componentProps: {
        maxlength: 100,
        clearable: true,
      },
    },
    {
      field: 'sort',
      component: 'NInputNumber',
      label: 'dictSort',
      defaultValue: 0,
      componentProps: {
        clearable: true,
        precision: 0,
        max: 99999,
        min: -99999,
      },
      rules: [
        {
          type: 'number',
          message: t('common.formTipMsg.input'),
          trigger: ['blur'],
        },
      ],
    },
    {
      field: 'remark',
      component: 'NInput',
      label: 'remark',
      defaultValue: '',
      componentProps: {
        type: 'textarea',
        'show-count': true,
        autosize: {
          minRows: 2,
          maxRows: 2,
        },
      },
    },
  ];

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({});
  const [modalFormRegister, { validate, getFieldsValue: getModalFormValFn, setFieldsValue }] =
    useForm({
      gridProps: { cols: 1 },
      collapsedRows: 3,
      labelWidth: 120,
      layout: 'horizontal',
      showActionButtonGroup: false,
      schemas: modalFormSchemas,
    });

const loadTableDataFn = async (res) => {
  console.log(dictTypeCode)
    return await getDictDataList({
      entity: {
        dictionaryTypeCode: dictTypeCode,
        languageType: queryLanguageType.value,
      },
      ...res,
    });
  };

  const reloadTableFn = () => {
    dictDataTableRef.value.clearRowKeysFn();
    dictDataTableRef.value.updatePage(1);
  };

  const selectLanguage = async (index) => {
    if (index === 0) {
      return;
    }
    selectLanguageType.value = [
      { active: 0, title: t('dictionary.selectLangTip') },
      { active: 0, title: t('dictionary.selectLangAll') },
      { active: 0, title: '简体中文' },
      { active: 0, title: 'English' },
    ];
    selectLanguageType.value[index].active = 1;
    queryLanguageType.value = ['', '', 'zh', 'en'][index];
    reloadTableFn();
  };

  const handleCheckedChange = async (val) => {
    currentCheckedRowKeys.value = val;
    deleteDisabled.value = !val.length;
  };

  const openModalFn = async (type, data = null) => {
    openModal(type, `${t(`common.button.${type}`)}${t('dictionary.moduleName')}`);
    editDisabled.value = type === 'edit';

    if (type === 'copy') {
      delete data.id
    }

    if (data) {
      nextTick(() => {
        setFieldsValue(data);
      });
    }
  };

  const modalSubmitFn = async () => {
    try {
      const isSubmit = await validate();
      if (!isSubmit) {
        setSubLoading(true);
        const data: any = {
          ...getModalFormValFn(),
          dictionaryTypeCode: dictTypeCode,
        };
        const res = editDisabled.value ? await updateDictData(data) : await addDictData(data);

        const { message: msg = '',code=200 } = res;

        if (res && code === 200) {

          closeModal();
          msg && message.success(msg || t('common.tipMsg.saveSuccess'));
          reloadTableFn();
        } else {
          setSubLoading(false);

          msg && message.error(msg || t('common.tipMsg.saveSuccess'));
        }
      }
    } catch (e) {
      console.log(e);
      setSubLoading(false);
    }
  };

  // const initDictData = async () => {
  //   getDictDataListFn('language_type').then((res) => {
  //     languageList.value = res || [];
  //   });
  // };

  // initDictData();
</script>

<style lang="less" scoped>
  .basicInfo-header {
    justify-content: flex-start;
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 16px;
    .language-select {
      display: flex;
      justify-content: center;
      align-items: center;
      li {
        font-size: 14px;
        font-weight: 400;
        text-align: center;
        color: #666666;
        line-height: 21px;
        padding: 4px 6px;
        margin-right: 8px;
        background: #eaeaea;
        border-radius: 2px;
        &.active {
          color: #0e4bb4;
          background: #ebf2ff;
          transition: 0.3s all;
        }
      }
      li:not(:first-child) {
        cursor: pointer;
      }
      li:first-child {
        background: none;
      }
    }
  }
</style>
